<?php

class User extends CActiveRecord
{
	const STATUS_NOACTIVE=0;
	const STATUS_ACTIVE=1;
	const STATUS_BANED=-1;
	
	/**
	 * The followings are the available columns in table 'users':
	 * @var integer $id
	 * @var string $username
	 * @var string $password
	 * @var string $email
	 * @var string $activkey
	 * @var integer $createtime
	 * @var integer $lastvisit
	 * @var integer $superuser
	 * @var integer $status
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return Yii::app()->getModule('user')->tableUsers;
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, password, unit_id, unit_level, email', 'required'),
			array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
			array('password', 'length', 'max'=>128, 'min' => 4,'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
			array('email', 'email'),
			array('telephone', 'length', 'max'=>14, 'min' => 7,'message' => UserModule::t('电话号码必须是7-14位')),
			array('username', 'unique', 'message' => UserModule::t("用户名已存在.")),
			array('surname',  'length', 'max'=>20, 'min' => 0,'message' => UserModule::t("用户名长度大于3小于20")),
			array('email', 'unique', 'message' => UserModule::t("邮箱地址已存在.")),
			array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("用户名必须是字母或数字.")),
			array('status', 'in', 'range'=>array(self::STATUS_NOACTIVE,self::STATUS_ACTIVE,self::STATUS_BANED)),
			array('unit_level', 'in', 'range'=>array(1,2,3,4),'message'=>'单位级别为必填项'),
			array('unit_id', 'match', 'pattern' => '/^[1-9]+\d*/u','message' => UserModule::t("单位必须选择.")),
			//array('superuser', 'in', 'range'=>array(0,1)),			
			array('createtime, lastvisit, status', 'numerical', 'integerOnly'=>true),
		);
		/*
		return ((Yii::app()->getModule('user')->isAdmin())?array(
			array('username, email, unit_id, unit_level', 'required'),
			array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
			array('password', 'length', 'max'=>128, 'min' => 4,'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
			array('email', 'email'),
			array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
			array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
			array('status', 'in', 'range'=>array(self::STATUS_NOACTIVE,self::STATUS_ACTIVE,self::STATUS_BANED)),
			array('unit_level', 'in', 'range'=>array(1,2,3,4),'message'=>'单位级别为必填项'),
			array('unit_id', 'match', 'pattern' => '/^[0-9]+$/u','message' => UserModule::t("单位为必填项.")),
			//array('superuser', 'in', 'range'=>array(0,1)),			
			array('createtime, lastvisit, status, unit_id', 'numerical', 'integerOnly'=>true),
		):((Yii::app()->user->id==$this->id)?array(
			array('username, email, unit_id, unit_level', 'required'),
			array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
			array('email', 'email'),
			array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
			array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
		):array(
			array('username, email, unit_id, unit_level', 'required'),
			array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
			array('email', 'email'),
			array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
			array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
		)));
		*/
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		$relations = array(
			'profile'=>array(self::HAS_ONE, 'Profile', 'user_id'),
		);
		if (isset(Yii::app()->getModule('user')->relations)) $relations = array_merge($relations,Yii::app()->getModule('user')->relations);
		return $relations;
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'username'=>UserModule::t("用户名"),
			'password'=>UserModule::t("密码"),
			'telephone'=>UserModule::t("电话"),
			'surname'=>UserModule::t("姓名"),
			'verifyPassword'=>UserModule::t("重复密码"),
			'email'=>UserModule::t("E-mail"),
			'verifyCode'=>UserModule::t("验证码"),
			'id' => UserModule::t("Id"),
			'activkey' => UserModule::t("activation key"),
			'createtime' => UserModule::t("注册时间"),
			'lastvisit' => UserModule::t("最后登录时间"),
			'superuser' => UserModule::t("超级管理员"),
			'status' => UserModule::t("状态"),
			'unit_id' => "所属单位",
			'unit_level' => "单位级别",
			'role'=>'角色',
		);
	}
	
	public function scopes()
    {
        return array(
            'active'=>array(
                'condition'=>'status='.self::STATUS_ACTIVE,
            ),
            'notactvie'=>array(
                'condition'=>'status='.self::STATUS_NOACTIVE,
            ),
            'banned'=>array(
                'condition'=>'status='.self::STATUS_BANED,
            ),
            'superuser'=>array(
                'condition'=>'superuser=1',
            ),
            'notsafe'=>array(
            	'select' => 'id, username, password, email, telephone, surname, activkey, createtime, lastvisit, superuser, status, unit_id, unit_level',
            ),
        );
    }
	
	public function defaultScope()
    {
        return array(
            'select' => 'id, username, email, telephone,surname, createtime, lastvisit, superuser, status, unit_id, unit_level',
        );
    }
	
	public static function itemAlias($type,$code=NULL) {
		$_items = array(
			'UserStatus' => array(
				self::STATUS_NOACTIVE => '不启用',//UserModule::t('Not active'),
				self::STATUS_ACTIVE => '启用',//UserModule::t('Active'),
				self::STATUS_BANED => '禁止',//UserModule::t('Banned'),
			),
			'AdminStatus' => array(
				'0' => UserModule::t('否'),
				'1' => UserModule::t('是'),
			),
		);
		if (isset($code))
			return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
		else
			return isset($_items[$type]) ? $_items[$type] : false;
	}
	
	public function getRole($user_id){
		$sql = 'select * from authitem where name in (select itemname from authassignment t where t.userid = '.$user_id.')';
		$command = Yii::app()->db->createCommand($sql);
		
		$db = $command->queryAll();
		$rolesArr = CHtml::listData($db,'name','description');	
		return CHtml::activeDropDownList(new AuthItem,'name',$rolesArr);	
	}
	
	public function getBases($user_id){
		$bases = array();
		$user = User::model()->findByPk($user_id);
		if(strripos($user->unit_id,',')){
			$feedback = $user->unit_id;
			
			$uid = strtok($feedback,',');
			while ($uid !== false) {
				$base =  MtsysBase::model()->findByPk($uid);
				$bases[] = $base;
				$uid = strtok(',');
			}
			
		}else{
			$base = MtsysBase::model()->findByPk($user->unit_id);
			$bases[] = $base;
		}
		
		return $bases;
	}
	
	public function getUnit($user_id){
		$unit = '';
		$user = User::model()->findByPk($user_id);
		switch($user->unit_level){
			case 0:
				$unit = "超级管理员";
				break;
			case 1:
				$unit = MtsysProvince::model()->findByPk($user->unit_id)->PROVINCE_NAME;
				break;
			case 2:
				$city =  MtsysCity::model()->findByPk($user->unit_id);
				$sheng = MtsysProvince::model()->find('PROVINCE_ID=:PID',array(
							':PID' => $city->PROVINCE_ID
				));
				$unit = $sheng->PROVINCE_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$city->CITY_NAME;
				break;
			case 3:
				$county =  MtsysCounty::model()->findByPk($user->unit_id);
				$city = MtsysCity::model()->find('CITY_ID=:CID',array(
					':CID' => $county->CITY_ID
				));
				$sheng = MtsysProvince::model()->find('PROVINCE_ID=:PID',array(
					':PID' => $city->PROVINCE_ID
				));
				$unit = $sheng->PROVINCE_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$city->CITY_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$county->COUNTY_NAME;
				break;
			case 4:
				if(strripos($user->unit_id,',')){
					$bases = array();
					
					$feedback = $user->unit_id;
					$basename = '(';
					$uid = strtok($feedback,',');	
					while ($uid !== false) {
						$base =  MtsysBase::model()->findByPk($uid);
						$basename = $basename . $base->BASE_NAME . ',';											
						$uid = strtok(',');
					}	
					$basename = $basename .')';
				}else{					
					$base = MtsysBase::model()->findByPk($user->unit_id);
					$basename = $base->BASE_NAME;
				}
				
				
				
				//$base = MtsysBase::model()->findByPk($user->unit_id);
				$county =  MtsysCounty::model()->find('COUNTY_ID=:CID',array(
					':CID' => $base->COUNTY_ID
				));
				$city = MtsysCity::model()->find('CITY_ID=:CID',array(
					':CID' => $base->CITY_ID
				));
				$sheng = MtsysProvince::model()->find('PROVINCE_ID=:PID',array(
					':PID' => $base->PROVINCE_ID
				));
				//$unit = $sheng->PROVINCE_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$city->CITY_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$county->COUNTY_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$base->BASE_NAME;
				$unit = $sheng->PROVINCE_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$city->CITY_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$county->COUNTY_NAME.'&nbsp;&nbsp;-&nbsp;&nbsp;'.$basename;				
				break;
		}	
		return $unit;
	}
}